package com.dmxtechnologies.community.ejb.interfaces.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.faces.context.FacesContext;

import com.dmxtechnologies.community.ejb.exception.CMSRuntimeException;
import com.dmxtechnologies.community.ejb.interfaces.JWHDetailTimeBroadcastRemote;
import com.dmxtechnologies.community.pojo.CMSDetailResponse;
import com.dmxtechnologies.community.rar.api.CMSBaseRequest;
import com.dmxtechnologies.community.rar.api.CMSConnection;
import com.dmxtechnologies.community.rar.api.CMSConnectionFactory;

/**
 * Session Bean implementation class JWHDetailTimeBroadcast
 */
@Singleton
public class JWHDetailTimeBroadcast implements JWHDetailTimeBroadcastRemote {
	private static final Logger log = Logger.getLogger("JWHDetailTimeBroadcast");
	@Resource(lookup = "java:global/env/eis/DMXCMSConnectionFactory")
	private CMSConnectionFactory connectionFactory;

    /**
     * Default constructor. 
     */
    public JWHDetailTimeBroadcast() {
        // TODO Auto-generated constructor stub
    }
    
    private Map<String, CMSDetailResponse> maps = new HashMap<String, CMSDetailResponse>();
    
    @Schedule(minute = "*/55", hour = "*", persistent = false)
	public void timer() {
		for (String id : maps.keySet()) {
			CMSDetailResponse detailResponse;
			// 229759_00406001_3047_47125_1
			CMSBaseRequest request = new CMSBaseRequest();
			request.setCommunity("229759");
			request.setPreColumns("00406001");
			request.setTemplateExample("3047");
			request.setNextColumns(id);
			request.setPagination(1);
			log.info("[ResourceAccessBean] Getting connection from the RA");
			try (CMSConnection connection = connectionFactory.getConnection();) {
				detailResponse = (CMSDetailResponse) connection
						.getContentDetailRequestToCMS(request);
				maps.put(id, detailResponse);
				log.info("invoke success");
			}catch (Exception e) {
				maps.remove(id);
				throw new CMSRuntimeException(e);
			}
		}
	}

	@Override
	public CMSDetailResponse getJWHDetailContent() throws Exception {
		String id = (String)FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id");
		log.info("enter:"+id);
		if(!maps.containsKey(id) || (maps.containsKey(id) && maps.get(id) == null) ){
			maps.put(id, null);
			timer();
		}
		return maps.get(id);
	}
}
